package JUC;

/**
 * 老版写法
 */
/*class Ticket{
    private int number = 1000;

    public synchronized void sale(){
        if (number>0) {
            System.out.println(Thread.currentThread().getName()+"\t卖出第"+(number--)+"\t还剩下"+number);
            System.out.println(Thread.currentThread().getName());
        }
    }
}

public class SaleTicket {

    public static void main(String[] args) {
         Ticket ticket = new Ticket();

        new Thread(new Runnable() {
            public void run() {
                for (int i = 1; i <= 2000; i++) {
                    ticket.sale();
                }
            }
        },"B").start();

        new Thread(new Runnable() {
            public void run() {
                for (int i = 1; i <= 2000; i++) {
                    ticket.sale();
                }
            }
        },"A").start();

        new Thread(()->{
            //insert your code here
        },"Thread name").start();



        System.out.println("hello");
    }

}*/

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 新版写法
 */

class Ticket {
    private int number = 3000;

    private final Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
        try {
            if (number>0) {
                System.out.println(Thread.currentThread().getName()+"\t卖出第"+(number--)+"\t还剩下"+number);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class SaleTicket {
    public static void main(String[] args) {

        Ticket ticket = new Ticket();
        new Thread(()->{for (int i = 0; i < 4000; i++) ticket.sale(); },"A").start();
        new Thread(()->{for (int i = 0; i < 4000; i++) ticket.sale(); },"B").start();


    }
}






